package com.zbkj.admin.pojo;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.mybatisflex.annotation.Column;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
import com.zbkj.admin.handler.TimestampToLocalDateTimeTypeHandler;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 商户分红期数记录 实体类。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Accessors(chain = true)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(name = "商户分红期数记录")
@TableName(value = "eb_dividend_record")
@Table(value = "eb_dividend_record")
public class EbDividendRecordEntity implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 主键Id
     */
    @Schema(description = "主键Id")
    @Id(value = "p_id", keyType = KeyType.Auto)
    @TableId(value = "p_id", type = IdType.AUTO)
    private Long id;

    /**
     * 商户Id
     */
    @Schema(description = "商户Id")
    @Column(value = "mer_id")
    @TableField(value = "mer_id")
    private Integer merId;

    /**
     * 当天交易流水总数(金额)
     */
    @Schema(description = "当天交易流水总数(金额)")
    @Column(value = "amount")
    @TableField(value = "amount")
    private BigDecimal amount;

    /**
     * 当前积分期,期数
     */
    @Schema(description = "当前积分期,期数")
    @Column(value = "num_of_periods")
    @TableField(value = "num_of_periods")
    private Integer numOfPeriods;

    /**
     * 分红池数量(金额)
     */
    @Schema(description = "分红池数量(金额)")
    @Column(value = "dividend_price")
    @TableField(value = "dividend_price")
    private BigDecimal dividendPrice;

    /**
     * 消费券数量(金额)
     */
    @Schema(description = "消费券数量(金额)")
    @Column(value = "consumer_coupon_price")
    @TableField(value = "consumer_coupon_price")
    private BigDecimal consumerCouponPrice;

    /**
     * 累计分红数量(金额)
     */
    @Schema(description = "累计分红数量(金额)")
    @Column(value = "count_price")
    @TableField(value = "count_price")
    private BigDecimal countPrice;

    /**
     * 释放期数状态(0:释放,1:未释放)
     */
    @Schema(description = "释放期数状态(0:释放,1:未释放)")
    @Column(value = "release_state")
    @TableField(value = "release_state")
    private Integer releaseState;

    /**
     * 分红时间
     */
    @Schema(description = "分红时间")
    @Column(value = "created_time", jdbcType = JdbcType.DATE, typeHandler = TimestampToLocalDateTimeTypeHandler.class)
    @TableField(value = "created_time", jdbcType = JdbcType.DATE, typeHandler = TimestampToLocalDateTimeTypeHandler.class)
    private LocalDateTime createdTime;

    /**
     * 操作人(商家)
     */
    @Schema(description = "操作人(商家)")
    @Column(value = "created_by")
    @TableField(value = "created_by")
    private String createdBy;

    /**
     * 手动释放(手动释放才会有基数)
     */
    @Schema(description = "手动释放(手动释放才会有基数)")
    @Column(value = "release_price")
    @TableField(value = "release_price")
    private BigDecimal releasePrice;

    /**
     * 释放信息
     */
    @Schema(description = "释放信息")
    @JsonDeserialize(keyUsing = NumericKeyDeserializer.class)
    @JsonSerialize(keyUsing = NumberKeySerializer.class)
    @Column(value = "expand", typeHandler = com.mybatisflex.core.handler.JacksonTypeHandler.class)
    @TableField(value = "expand", typeHandler = FastjsonTypeHandler.class)
    private List<Long> expand;

    /**
     * 循环周期数(36期或40期算一轮)
     */
    @Builder.Default
    @Schema(description = "循环周期数(36期或40期算一轮)")
    @Column(value = "cycle")
    @TableField(value = "cycle")
    private Long cycle = 1L;

    /**
     * 发放次数
     */
    @Builder.Default
    @Schema(description = "发放次数")
    @Column(value = "record_times")
    @TableField(value = "record_times")
    private Integer recordTimes = 1;

    /**
     * 发放次数
     */
    @TableLogic
    @Builder.Default
    @Schema(description = "发放次数")
    @Column(value = "del_fled", isLogicDelete = true)
    @TableField(value = "del_fled")
    private Integer delFled = 0;

    /**
     * 是否立即释放
     */
    @Schema(description = "是否立即释放")
    @Column(ignore = true)
    @TableField(exist = false)
    private Boolean isDividend;

    /**
     * 释放百分比数值
     */
    @Schema(description = "释放百分比数值")
    @Column(ignore = true)
    @TableField(exist = false)
    private BigDecimal percentage;


    /**
     * 积分池释放信息
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public static class ReleaseInfo implements Serializable {

        @Serial
        private static final long serialVersionUID = 1L;

        /**
         * 用户Id
         */
        private Long uid;

        /**
         * 释放用户明细
         */
        private Map<String, Object> cycleUserDetails;

        /**
         * 商品信息
         */
        private Map<String, Object> productInfo;

        /**
         * 汇总商品积分总和信息
         */
        private Map<String, Map<Long, Object>> summaryProductInfo;

        /**
         * 秒杀商品信息
         */
        private Map<Long, Object> seckillProductInfo;

        /**
         * 释放期数
         */
        private Long cycle;

    }

    // 自定义反序列化器
    public static class NumericKeyDeserializer extends KeyDeserializer {
        @Override
        public Object deserializeKey(String key, DeserializationContext ctxt) {
            try {
                return new BigDecimal(key);
            } catch (NumberFormatException e) {
                return key; // 根据业务需求处理非数字键
            }
        }
    }

    public static class NumberKeySerializer extends JsonSerializer<String> {
        @Override
        public void serialize(String key, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            // 尝试将String键转为Integer
            if (Validator.isNumber(key)) {
                gen.writeFieldId(Integer.parseInt(key)); // 或根据实际类型调整
            } else {
                gen.writeFieldName(key);
            }
        }
    }

}
